import {Component, OnInit} from '@angular/core';
import {Globals} from "../../../globals";
import {PageHelper} from "../../../utils/page-helper-model";
import {FormGroup} from "@angular/forms";
import {ApiUrl} from "../../../config/api-url";
import {BaseService} from "../../../shared/service/base.service";
import {ActivatedRoute, NavigationEnd, Router} from "@angular/router";
import {Consts} from "../../../config/consts";
import {RoleIdEnum} from "../../../enums/role-id.enum";
import {filter} from 'rxjs/operators';
import {Withdrawals} from '../../../../../_mock/withdrawals';

@Component({
  selector: 'app-withdrawals-list',
  templateUrl: './withdrawals-list.component.html',
  styleUrls: ['./withdrawals-list.component.less']
})
export class WithdrawalsListComponent implements OnInit {
  isMobile = Globals.isMobile();
  listOfData: any;
  // 分页
  pageHelper: PageHelper = new PageHelper;
  formModel: FormGroup;
  // 头部
  isBatchDeal = true;
  // 角色
  roleId: number;

  // 全选框
  checkOptions = {};
  indeterminate = false;
  // 单个选框
  withdrawList = [];
  // 加载状态
  isSpinning: boolean;
  // 拒绝原因
  failReason: string;
  // 验证码
  smsCode: string;

  isVisible: boolean;
  accountIsVisible: boolean;
  moneyWithdraw: any;
  // 查询参数
  updateTime: Date;
  createTime: Date;
  status: -1;
  moneyPending: number;
  moneyDispose: number;
  remark: string;
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
  };

  withDrewStatus = -1;

  // 公众号二维码路径
  isSendCode: boolean;
  // 时间
  timer: any;
  smsCodeText = '发送验证码';
  isLoading: boolean;
  isVisibleInvoice: boolean;
  constructor(private baseService: BaseService, private activatedRoute: ActivatedRoute, private router: Router) {
    // this.activatedRoute.queryParams.subscribe(params => {
    //   console.log("-----------跳转-----------")
    //   this.getAgentsData();
    // });
    this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe(event => {
      let url = event['url'];
      console.log(url)
      if ('/withdrawals/withdrawals-list?r=1' == url) {
        this.getAgentsData();
        this.findMoneyWithdrawStatistics();
      }
    });
  }

  ngOnInit(): void {
    this.roleId = JSON.parse(sessionStorage.getItem(Consts.USER_INFO)).roleId;
    this.getAgentsData();
    this.findMoneyWithdrawStatistics();
  }

  onPageSizeChange(pageSize: any){
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.getAgentsData();
  }
  into() {
    this.pageHelper.currentPage = 1;
    this.getAgentsData();
    this.findMoneyWithdrawStatistics();
  }

  getAgentsData() {
    let body = {
      status: this.status,
      createTime: this.createTime,
      updateTime: this.updateTime,
    }
    // this.listOfData = Withdrawals;
    this.baseService.findListByMuchCondition(ApiUrl.MoneyWithdrawUrl + '/list', body, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          this.pageHelper.totalItems = data.data.total;
          this.listOfData = data.data.list;
          this.withdrawList = [];
          data.data.list.forEach(item => {
            this.checkOptions[item.id] = false;
          });
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  // 进入申请提现如果没有绑定银行卡则弹出绑定结算卡绑定的页面
  addWithdrawals() {
    this.baseService.get(ApiUrl.UserBankCardUrl + '/checkUserBankCard').subscribe(data => {
      if (data.data <= 0) {
        this.baseService.layer.modalConfirm('你还没绑定银行卡,是否绑定', confirm => {
          if (confirm) {
            this.isVisible = true;
          }
        });
      } else {
        this.router.navigateByUrl('/withdrawals/withdrawals-edit');
      }
    });
  }

  emitBindBankCard($event) {
    this.isVisible = $event;
  }

  findMoneyWithdrawStatistics() {
    let body = {
      createTime: this.createTime,
      updateTime: this.updateTime,
      keyword: this.pageHelper.keyword
    }
    this.baseService.post(ApiUrl.MoneyWithdrawUrl + '/findMoneyWithdrawStatistics', body).subscribe(
      data => {
        if (data.status == 0) {
          this.moneyPending = data.data?.moneyPending;
          this.moneyDispose = data.data?.moneyDispose
          console.log(data);
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }


  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.getAgentsData();
    this.findMoneyWithdrawStatistics();
  }

  withDrawalsSearch($event) {
    this.pageHelper.currentPage = 1;
    this.pageHelper.keyword = $event.keyword;
    this.status = $event.status;
    this.withDrewStatus = $event.status;
    this.createTime = $event.startDateTime;
    this.updateTime = $event.endDateTime;
    this.getAgentsData();
    this.findMoneyWithdrawStatistics();
  }
  showInvoice() {
    this.isVisibleInvoice = true;
  }

  eventInvoice($event: any) {
    this.isVisibleInvoice = $event;
  }

  /**
   * 全选框
   */
  updateAllChecked(value: boolean) {
    this.listOfData.forEach(item => this.checkOptions[item.id] = value);
    if (value) {
      this.withdrawList = [];
      this.listOfData.forEach(
        item => this.withdrawList.push(item)
      );
    } else {
      this.withdrawList = [];
    }
  }

  /**
   * 单框复选
   */
  signalCheck(event, item) {
    if (event) {
      this.withdrawList.push(item);
    } else {
      this.withdrawList = this.withdrawList.filter(entity => entity.id != item.id);
      if (this.withdrawList.length <= 0) {
      }
    }
  }

  // 处理提现按钮
  disposeMoney(data) {
    console.log(data.invoiceStatus);
    const msg = data.signInStatus ? '' : '该提现还没收到发票签收，';
    this.baseService.layer.modalConfirm(msg + '确定要处理吗？', confirm => {
      if (confirm) {
        this.isSpinning = true;
        data.receivestatus = 1;
        this.failReason = null;
        this.dispose(data);
        this.indeterminate = false;
      }
    });
  }

  // 手动打款
  manualMoneyRemit(data, manualMoney) {
    this.baseService.layer.createTplModal('确定手动打款吗？请输入手动打款原因', manualMoney, confirm => {
      if (confirm) {
        if (this.remark == null || this.remark == '') {
          this.baseService.layer.modalError('请输入手动打款原因');
          return;
        }
        this.isSpinning = true;
        data.receivestatus = 2;
        this.failReason = null;
        this.dispose(data);
        this.indeterminate = false;
      }
    });
  }

  // 拒绝提现
  repulseMoney(data, tplContent) {
    this.baseService.layer.createTplModal('请输入拒绝原因', tplContent, confirm => {
      if (confirm) {
        if (this.failReason == null || this.failReason == '') {
          this.baseService.layer.modalError('请输入拒绝原因');
          return;
        }
        this.isSpinning = true;
        data.receivestatus = 3;
        this.dispose(data);
        this.failReason = null;
        this.indeterminate = false;
      }
    });
  }

  // 代付打款
  daiFuMoneyRemit(data) {
    let reg = /^[0-9]{6}$/;
    if (!reg.test(this.smsCode)) {
      this.baseService.layer.modalError('请输入有效验证码!');
      return;
    }
    this.baseService.layer.modalConfirm('确定代付打款吗？', confirm => {
      if (confirm) {
        this.isSpinning = true;
        data.receivestatus = 4;
        this.failReason = '';
        let body = [{
          status: data.receivestatus,
          id: data.id,
          withdrawType: data.withdrawType,
          userId: data.userId,
          money: data.money,
          smsCode: this.smsCode,
        }];
        this.daifuRemit(body);
      }
    });
  }

  // 处理代付打款
  daifuRemit(body) {
    this.baseService.put(ApiUrl.MoneyWithdrawUrl + '/daiFuBalance', body).subscribe(data => {
      if (data.status == 0) {
        this.getAgentsData();
        this.findMoneyWithdrawStatistics();
        this.isSpinning = false;
        this.baseService.layer.messageSuccess(data.data);
      } else {
        this.isSpinning = false;
        this.baseService.layer.modalError(data.msg);
        this.getAgentsData();
        this.findMoneyWithdrawStatistics();
      }
    });
    // this.baseService.daiFuBalance(this.smsCode, body, data => {
    //   this.isSpinning = false;
    //   if (data.status == 0) {
    //     this.searchMoneyWithdrawInfo();
    //     this.layer.messageSuccess(data.data);
    //   } else {
    //     this.layer.modalError(data.msg);
    //     this.searchMoneyWithdrawInfo();
    //   }
    // });
  }


  // 处理提现,拒绝提现，手动打款,可以多个一起处理所以要传集合
  dispose(data) {
    const body = [{
      status: data.receivestatus,
      failReason: this.failReason,
      remark: this.remark,
      id: data.id,
      withdrawType: data.withdrawType,
      userId: data.userId,
      money: data.money,
      type: data.type,
    }];
    this.baseService.put(ApiUrl.MoneyWithdrawUrl, body).subscribe(res => {
      console.log(res);
      if (res.status == 0) {
        this.isSpinning = false;
        this.getAgentsData();
        this.findMoneyWithdrawStatistics();
      } else {
        this.baseService.layer.messageError(res.msg);
        this.isSpinning = false;
      }
      this.remark = null;
    });
  }

  batchDeal() {
    if (this.withdrawList.length <= 0) {
      this.baseService.layer.messageError('请至少选择一个处理对象')
      return;
    }
    for (const any of this.withdrawList) {
      if (any.status != 0) {
        this.baseService.layer.messageError(any.userName + '不能进行处理操作');
        return;
      }
    }
    this.baseService.layer.modalConfirm('确定要处理吗？', confirm => {
      if (confirm) {
        let body = [];
        this.withdrawList.forEach(item => body.push({
          id: item.id,
          status: 1,
          failReason: confirm
        }));
        console.log(body)
        this.baseService.put(ApiUrl.MoneyWithdrawUrl, body).subscribe(res => {
          this.indeterminate = false;
          this.into();
        });
      }
    });
  }

  batchDealRefuse(tplContent) {
    console.log(this.withdrawList)
    if (this.withdrawList.length <= 0) {
      this.baseService.layer.messageError('请至少选择一个拒绝对象');
      return;
    }
    for (let any of this.withdrawList) {
      if (!(any.status == 1 || any.status == 5)) {
        this.baseService.layer.messageError(any.userName + '不能进行拒绝操作!');
        return;
      }
    }
    this.baseService.layer.createTplModal('请输入拒绝原因', tplContent, confirm => {
      if (confirm) {
        if (this.failReason == null || this.failReason == '') {
          this.baseService.layer.modalError('请输入拒绝原因');
          return;
        }
        let body = [];
        this.withdrawList.forEach(item => body.push({
          id: item.id,
          userId: item.userId,
          withdrawType: item.withdrawType,
          money: item.money,
          status: 3,
          type: item.type,
          failReason: this.failReason
        }));
        this.baseService.put(ApiUrl.MoneyWithdrawUrl, body).subscribe(res => {
          this.indeterminate = false;
          this.into();
          this.failReason = null;
        });
      }
    });
  }

  // 获取验证码
  sendCode() {
    console.log("是否进入")
    if (this.withdrawList.length <= 0) {
      this.baseService.layer.messageError('请至少选择一个拒绝对象');
      return;
    }
    for (const any of this.withdrawList) {
      if ((any.status == 1 || any.status == 5) && any.invoiceFlag == '01') {
      } else {
        this.baseService.layer.modalError(any.username + '不能代付打款操作!');
        return;
      }
    }
    this.isLoading = true;
    if (!this.isSendCode) {
      this.baseService.get(ApiUrl.SmsCodeUrl + '/sendCode').subscribe(res => {
        if (res.status == 0) {
          clearInterval(this.timer);
          this.isSendCode = true;
          let time = 59;
          this.timer = setInterval(() => {
            if (time > 0) {
              time--;
              this.smsCodeText = time + '秒 重新发送';
            } else {
              this.smsCodeText = '重新发送';
              this.isSendCode = false;
              // 清除计时器
              clearInterval(this.timer);
            }
            this.isLoading = false;
          }, 1000);
          this.baseService.layer.messageSuccess(res.data);
        } else {
          this.isLoading = false;
          this.baseService.layer.messageError(res.msg);
        }
      });
    } else {
      this.baseService.layer.modalError('请稍后重试!');
    }
  }

  // 批量代付
  batchDealMoney() {
    if (this.withdrawList.length <= 0) {
      this.baseService.layer.modalError('请至少选择一个代付打款对象');
      return;
    }
    for (let any of this.withdrawList) {
      if ((any.status == 1 || any.status == 5) && any.invoiceFlag == '01') {
      } else {
        this.baseService.layer.modalError(any.userName + '不能代付打款, 请核对!');
        return;
      }
    }
    let reg = /^[0-9]{6}$/;
    if (!reg.test(this.smsCode)) {
      this.baseService.layer.modalError('请输入有效验证码!');
      return;
    }
    this.withdrawList[0].smsCode = this.smsCode;
    this.baseService.layer.modalConfirm('确定要处理吗？', confirm => {
      if (confirm) {
        this.baseService.put(ApiUrl.MoneyWithdrawUrl + '/daiFuBalance', this.withdrawList).subscribe(data => {
          // this.baseService.daiFuBalance(this.smsCode,this.withdrawList,data=>{
          if (data.status == 0) {
            this.indeterminate = false;
            this.into()
            this.baseService.layer.messageSuccess(data.data);
          } else {
            this.baseService.layer.modalError(data.msg);
            this.indeterminate = false;
            this.into();
          }
        });
      }
    });
  }


  AccountInfo($event) {
    this.accountIsVisible = $event;
  }

  showAccountInfo(data: any) {
    this.accountIsVisible = true;
    this.moneyWithdraw = data;
  }

  skipStatistics(data: any) {
    if (data.withdrawType == 1) {
      this.router.navigateByUrl('/statistic/user-statistic?username=' + data.userName,
        {skipLocationChange: true});
    } else {
      this.router.navigateByUrl('/statistic/agency-statistic?username=' + data.userName,
        {skipLocationChange: true});
    }

  }

  changeRadio() {
    // console.log(this.status)
    this.withDrewStatus = -1;
    this.pageHelper.currentPage = 1;
    this.getAgentsData();
    this.findMoneyWithdrawStatistics();
  }
}
